package admin

import (
	"context"

	"suci-go-zero/common/xerr"
	"suci-go-zero/internal/model"
	"suci-go-zero/internal/svc"
	"suci-go-zero/internal/types"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type RoleAddLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewRoleAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RoleAddLogic {
	return &RoleAddLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *RoleAddLogic) RoleAdd(req *types.Role) error {
	rb := l.svcCtx.Models.Role.RowBuilder().Where("label=?", req.Label)
	role, err := l.svcCtx.Models.Role.FindOneByQuery(l.ctx, rb)
	if err != nil && err != model.ErrNotFound {
		return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "添加校色,校色查找失败%v", err)
	}
	if role != nil {
		return errors.Wrapf(xerr.NewErrCodeMsg(xerr.DB_ALREADY_EXIST, "角色已存在"), "角色已存在")
	}

	_, err = l.svcCtx.Models.Role.Insert(l.ctx, nil, &model.AdminRole{
		Alias:  req.Alias,
		Label:  req.Label,
		Remark: req.Remark,
		Sort:   int64(req.Sort),
		Status: int64(req.Status),
	})

	if err != nil {
		return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "插入校色失败%v", err)
	}

	return nil
}
